package top.tresman.cxxcommon.utils;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import top.tresman.cxxcommon.entity.constants.ErrorCodeEnum;
import top.tresman.cxxcommon.exception.ApiException;

@Data
public class GenCodeUtils {
    public void doGen(GenParam genParam) {
        if (StringUtils.isBlank(genParam.jdbcUrl)) {
            throw new ApiException(ErrorCodeEnum.BAD_ARGS, "数据库连接参数不能为空");
        }
        if (StringUtils.isBlank(genParam.username)) {
            throw new ApiException(ErrorCodeEnum.BAD_ARGS, "数据库用户名不能为空");
        }
        if (StringUtils.isBlank(genParam.password)) {
            throw new ApiException(ErrorCodeEnum.BAD_ARGS, "密码不能为空");
        }
        if (StringUtils.isBlank(genParam.outputDir)) {
            throw new ApiException(ErrorCodeEnum.BAD_ARGS, "输出目录不能为空");
        }
        if (StringUtils.isBlank(genParam.basePackage)) {
            throw new ApiException(ErrorCodeEnum.BAD_ARGS, "输出包名不能为空");
        }
        FastAutoGenerator.create(genParam.jdbcUrl, genParam.username, genParam.password)
                .globalConfig(builder -> builder
                        .author("cxx")
                        .outputDir(genParam.outputDir)
                        .commentDate("yyyy-MM-dd")
                )
                .packageConfig(builder -> builder
                        .parent(genParam.basePackage)
                        .entity("entity")
                        .mapper("mapper")
                        .service("service")
                        .serviceImpl("service.impl")
                        .xml("xml")
                )
                .strategyConfig(builder -> builder
                        .addTablePrefix("l_")
                        .entityBuilder()
                        .enableLombok()
                )
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    @Data
    public static class GenParam {
        private String jdbcUrl;
        private String username;
        private String password;
        private String outputDir;
        private String basePackage;
    }
}
